package com.example.xm.ui.own.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.Editable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;

import com.example.xm.R;
import com.example.xm.app.GlideEngine;
import com.example.xm.base.BaseActivity;
import com.example.xm.bean.OwnBean.UserUpdateBean;
import com.example.xm.interfaces.own.IOwn;
import com.example.xm.model.HttpManager;
import com.example.xm.model.OwnApi.UploadApi;
import com.example.xm.presenter.own.OwnPresenter;
import com.example.xm.utiles.EditEnableUtils;
import com.example.xm.utiles.GildeUtils;
import com.example.xm.utiles.ImageUtil;
import com.example.xm.utiles.SpUtils;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class DetailEditActivity extends BaseActivity<IOwn.Presenter> implements IOwn.View {
    @BindView(R.id.img_back)
    ImageView imgBack;
    @BindView(R.id.img_head)
    ImageView imgHead;
    @BindView(R.id.tv_edit_editdetail)
    TextView tvEditEditdetail;
    @BindView(R.id.rl_head)
    RelativeLayout rlHead;
    @BindView(R.id.tv_photo_num)
    EditText tvPhotoNum;
    @BindView(R.id.rl_photo)
    RelativeLayout rlPhoto;
    @BindView(R.id.tv_sex_editdetail)
    EditText tvSexEditdetail;
    @BindView(R.id.rl_sex)
    RelativeLayout rlSex;
    @BindView(R.id.tv_shengri_num)
    EditText tvShengriNum;
    @BindView(R.id.rl_shengri)
    RelativeLayout rlShengri;
    @BindView(R.id.tv_dizhi_editdetail)
    EditText tvDizhiEditdetail;
    @BindView(R.id.rl_dizhi)
    RelativeLayout rlDizhi;
    @BindView(R.id.tv_name_edit)
    EditText tvNameEdit;
    @BindView(R.id.rl_name)
    RelativeLayout rlName;
    @BindView(R.id.tv_age_num)
    EditText tvAgeNum;
    @BindView(R.id.rl_age)
    RelativeLayout rlAge;
    @BindView(R.id.tv_qianming)
    TextView tvQianming;
    @BindView(R.id.et_qianming)
    EditText etQianming;
    @BindView(R.id.rl_qianming)
    ConstraintLayout rlQianming;

    @Override
    protected IOwn.Presenter initPresenter() {
        return new OwnPresenter();
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_editdetail;
    }

    @Override
    protected void initView() {
        String avater = SpUtils.getInstance().getString("avater");
        String phone = SpUtils.getInstance().getString("phone");
        GildeUtils.loadRoundImg(this, avater, imgHead);
        tvPhotoNum.setText(phone);
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initListener() {
        tvEditEditdetail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (tvEditEditdetail.getText().equals("编辑")) {
                    tvEditEditdetail.setText("完成");
                    EditEnableUtils.EditTextEnable(true, tvNameEdit);
                    EditEnableUtils.EditTextEnable(true, tvAgeNum);
                    EditEnableUtils.EditTextEnable(true, tvPhotoNum);
                    EditEnableUtils.EditTextEnable(true, tvDizhiEditdetail);
                    EditEnableUtils.EditTextEnable(true, tvSexEditdetail);
                    EditEnableUtils.EditTextEnable(true, tvShengriNum);
                } else {
                    tvEditEditdetail.setText("编辑");
                    EditEnableUtils.EditTextEnable(false, tvNameEdit);
                    EditEnableUtils.EditTextEnable(false, tvAgeNum);
                    EditEnableUtils.EditTextEnable(false, tvPhotoNum);
                    EditEnableUtils.EditTextEnable(false, tvDizhiEditdetail);
                    EditEnableUtils.EditTextEnable(false, tvSexEditdetail);
                    EditEnableUtils.EditTextEnable(false, tvShengriNum);
                    String phone = tvPhotoNum.getText().toString();
                    upLoadPhone(phone);
                }
            }
        });
    }

    //上传电话号码
    private void upLoadPhone(String phone) {
        Map<String, String> map = new HashMap<>();
        map.put("phone", phone);
        String token = SpUtils.getInstance().getString("token");
        //更新服务器上的头像
        mPresenter.updateUserInfo(token, map);
        SpUtils.getInstance().setValue("phone", phone);
        Toast.makeText(DetailEditActivity.this, "上传成功", Toast.LENGTH_SHORT).show();
    }

    private static final String TAG = "DetailEditActivity";

    @Override
    public void updateUserInfoReturn(UserUpdateBean result) {


        Log.d(TAG, "updateUserInfoReturn: " + result.toString());
    }

    @OnClick({R.id.img_back, R.id.img_head})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_back:
                finish();
                break;
            case R.id.img_head:
//                openPhoto();
                Intent intent = new Intent(Intent.ACTION_PICK);
                intent.setType("image/*");
                startActivityForResult(intent, 200);
                break;
        }
    }

    //打开相册图片的选择界面
    private void openPhoto() {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .loadImageEngine(GlideEngine.createGlideEngine()) // Please refer to the Demo GlideEngine.java
                .maxSelectNum(1)
                .imageSpanCount(4)
                .enableCrop(true)
                .selectionMode(PictureConfig.MULTIPLE)
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }

    /**
     * 获取相机相册图片
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //从图库选图片裁剪
        if (requestCode == 200 && resultCode == RESULT_OK) {
            Uri uri = data.getData();
            Intent intent = new Intent("com.android.camera.action.CROP");
            intent.setDataAndType(uri, "image/*");
            intent.putExtra("crop", true);
            //缩放比例
            intent.putExtra("asceptX", 1);
            intent.putExtra("asceptY", 1);
            //大小
            intent.putExtra("outputX", 250);
            intent.putExtra("outputY", 250);
            //把图片数据直接通过intent返回
            intent.putExtra("return-data", true);
            startActivityForResult(intent, 300);
        }
        //caijianwancheng
        if (requestCode == 300 && resultCode == RESULT_OK) {
            Bitmap bitmap = data.getParcelableExtra("data");
            //将图片保存为文件
            File file = new File(createImageFilePath());
            try {
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(file));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            // 缩放 减小分辨率 影响图片文件大小，加载到内存中占用的大小
            // 压缩 降低图片质量 不影响分辨率， 影响图片文件大小，加载到内存中占用的大小不变
            //缩放（调用ImageUtil中的缩放方法）
            Bitmap bitmap1 = ImageUtil.scaleBitmap(file.getAbsolutePath(), 100, 100);
            //压缩（调用ImageUtil中的压缩方法）
            ImageUtil.compressImage(bitmap1, 70, file.getAbsolutePath());
            String absolutePath = file.getAbsolutePath();
            uploadImage(absolutePath);
            //加载最终图片结果
            bitmap1 = BitmapFactory.decodeFile(file.getAbsolutePath());
            //设置图片
            imgHead.setImageBitmap(bitmap);
        }
    }

    private String createImageFilePath() {
        //getCacheDir();
        //裁剪之后的图片（每裁剪一次会覆盖之前的裁剪图片）
        return Environment.getExternalStorageDirectory().getAbsolutePath() + "/r.png";
    }

    /**
     * 缺少图片上传的功能
     *
     * @param path
     */
    private void uploadImage(String path) {
        String img_format = "image/jpg";
        String key = "1909";
        //sd卡图片文件
        File file = new File(path);
        //文件存在
        if (file.exists()) {
            RequestBody requestFile = MultipartBody.create(MediaType.parse(img_format), file);
            //创建一个MultipartBody.Part 封装的文件数据（文件流） file参数是给后台接口读取文件用，file.getName() 保存到后台的文件名字
            String filename = UUID.randomUUID().toString() + ".jpg";
            MultipartBody.Part part = MultipartBody.Part.createFormData("file", filename, requestFile);
            //设置对应的key application/json; charset=utf-8
            RequestBody key_file = RequestBody.create(MediaType.parse("multipart/form-data"), key);
            //通过requestbody传值到后台接口
            //RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"),key);
            //创建retrofit
            UploadApi uploadApi = HttpManager.getInstance().getUploadApi();
            Call<ResponseBody> call = uploadApi.uploadFile(key_file, part);
            call.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    try {
                        String result = response.body().string();
                        if (!TextUtils.isEmpty(result)) {
                            JSONObject json = new JSONObject(result);
                            int code = json.getInt("code");
                            if (code == 200) {
                                JSONObject dataJson = new JSONObject(json.getString("data"));
                                String url = dataJson.getString("url");
                                Map<String, String> map = new HashMap<>();
                                map.put("avater", url);
                                String token = SpUtils.getInstance().getString("token");
                                //更新服务器上的头像
                                mPresenter.updateUserInfo(token, map);
                                SpUtils.getInstance().setValue("avater", url);
                                Toast.makeText(DetailEditActivity.this, "上传成功", Toast.LENGTH_SHORT).show();
                            }
                        }
                        Log.i("onResponse", response.body().string());
                    } catch (IOException | JSONException e) {
                        e.printStackTrace();
                        Log.i("e", "解析上传结果json失败");
                    }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                    Log.i("onFailure", t.getMessage());
                }
            });
        } else {
            Toast.makeText(this, "找不到本地文件", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void showTips(String tips) {

    }

    @Override
    public void showLoading(int visble) {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
